package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.fastdfs.FastDFSClient;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.MaterialService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Log4j2
public class MaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial>implements MaterialService {
    @Autowired
    private FastDFSClient fastDFSClient;
    @Value("${fdfs.url}")
    private String url;
    @Override
    public ResponseResult upLoadFile(MultipartFile multipartFile) {
        //1.检查参数
        if(multipartFile==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.上传到fastdfs
        String file=null;
        try {
           file = fastDFSClient.uploadFile(multipartFile);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        //3.保存到数据库中
        WmUser user = WmThreadLocalUtils.getUser();
        WmMaterial material = new WmMaterial();
        material.setCreatedTime(new Date());
        material.setUserId(user.getId());
        material.setIsCollection((short)0);
        material.setUrl(file);
        material.setType((short)0);
        save(material);
        material.setUrl(url+file);
        return ResponseResult.okResult(material);
    }

    @Override   //素材列表
    public ResponseResult findList(WmMaterialDto dto) {
        //1.检查参数
        dto.checkParam();
        WmUser user = WmThreadLocalUtils.getUser();
        IPage<WmMaterial> wpage=new Page<>(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmMaterial::getUserId,user.getId());
        //是否收藏
        if(dto.getIsCollection() != null && dto.getIsCollection().shortValue()==1){//收藏列表
            wrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        wrapper.orderByDesc(WmMaterial::getCreatedTime);//按照日期倒序排序
        IPage<WmMaterial> page = page(wpage, wrapper);
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        List<WmMaterial> list = page.getRecords();
        /*list=list.stream().map(item->{//为每个图片都添加前缀
            item.setUrl(url+item.getUrl());
            return item;
        }).collect(Collectors.toList());*/
        for (WmMaterial material : list) {
            material.setUrl(url+material.getUrl());
        }
        result.setData(list);
        return result;
    }
    @Autowired
    private WmNewsMaterialMapper newsMaterialMapper;
    @Override //删除图片
    public ResponseResult delPicture(Integer id) {
        //1.参数检查
        if(id==null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmMaterial wmMaterial = getById(id);
        if(wmMaterial==null){//判断数据库中是否有该图片
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.判断是否被引用
        LambdaQueryWrapper<WmNewsMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmNewsMaterial::getMaterialId,id);
        Integer count = newsMaterialMapper.selectCount(wrapper);
        if(count>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH,"当前数据被引用，无法删除");
        }
        //3.删除dfs中的图片
        String fileId=wmMaterial.getUrl().replace(url,"");//以防有http开头那部分前缀，替换掉
        try {
            fastDFSClient.delFile(fileId);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        //4.删除数据库中的图片
        removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
    @Override   //收藏与取消收藏图片
    public ResponseResult updateStatus(Integer id, Short type) {
        //1.参数判断
        if(id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.修改收藏状态
        WmUser wmUser = WmThreadLocalUtils.getUser();
        WmMaterial wmMaterial = getById(id);
        wmMaterial.setIsCollection(type);
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmMaterial::getUserId,wmUser.getId()).eq(WmMaterial::getId,id);
        try {
            update(wmMaterial,wrapper);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"收藏失败");
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS);
    }
}
